package com.umanji.building;

import java.io.FileNotFoundException;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import java.util.Collections;



import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import javax.persistence.NoResultException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.util.WebUtils;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.umanji.building.domain.BuildingInfos;
import com.umanji.building.domain.PublicOfficialBuildingBoards;
import com.umanji.building.domain.PublicOfficialBuildings;

import com.umanji.building.domain.Buildings;
import com.umanji.building.service.BuildingService;
import com.umanji.building.service.PublicOfficialBuildingBoardService;
import com.umanji.building.service.PublicOfficialBuildingService;
//import com.umanji.postgis.domain.PostGISBuilding;
import com.umanji.page.*;
import com.umanji.postgis.domain.Tbbi001;

import com.umanji.postgis.service.PostgisService;
import com.umanji.user.UserController;


/**
 * Handles requests for the application welcome page.
 */
@Controller
@RequestMapping(value="/pobuilding")
public class PublicOfficialBuildingController {

	private Logger logger = org.slf4j.LoggerFactory.getLogger(PublicOfficialBuildingController.class);

	private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
	
	@Autowired
	public PublicOfficialBuildingController(Validator validator) {
		this.validator = validator;
	}

    @Autowired
    private PublicOfficialBuildingService buildingService;

    @Autowired
    private PublicOfficialBuildingBoardService pobBoardService;
    
    @Autowired
    private PostgisService postgisService;
    
    
    //자치센터 글입력폼 페이지 이동
    @RequestMapping(value = "/write/{buildingNo}", method = RequestMethod.GET)
	public ModelMap goWritePublic(@PathVariable String buildingNo, ModelMap modelMap) {
    	Tbbi001 gisBuildingInfo = postgisService.findByBuildingNo(buildingNo);
    	try {
    		PublicOfficialBuildings building = buildingService.findByPobNo(buildingNo);
		} catch (NoResultException e) {
			PublicOfficialBuildings building = new PublicOfficialBuildings( );
			building.setBuildingNo(buildingNo);
			building.setName(gisBuildingInfo.getBuildingDetailName());
			building.setDivision(gisBuildingInfo.getBuildingMemo());

			buildingService.persist(building);
		} 
		
		ModelMap model = new ModelMap("gisBuildingInfo", gisBuildingInfo);
		PublicOfficialBuildingBoards buildingBoard = new PublicOfficialBuildingBoards( );
		model.addAttribute("umj_building_board", buildingBoard);
		System.out.println("ㅎㅎㅎ get 통과했음");
		return model;
		
	}
    
    //자치센터 글입력 메소드
    @RequestMapping(value = "/write/{buildingNo}", method = RequestMethod.POST)
    public String writePublic(@PathVariable String buildingNo, 
    							@RequestParam("title") String title,
    							@RequestParam("content") String content,
    							//@RequestParam("")CommonsMultipartFile img,
    							HttpServletRequest request){
    	logger.info("register building board!");
    	
    	try {
    		PublicOfficialBuildings building = buildingService.findByBuildingNo(buildingNo);
    		
			String rootPath = WebUtils.getRealPath(request.getSession().getServletContext(), "upload");
			//building.setImgFile( building.getSavedFileName(rootPath, buildingImageFile, "building") );
				
				String name="";
				Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
				if (principal instanceof UserDetails) {
					name = ((UserDetails) principal).getUsername();
				}
				Date regDate = new Date();
				System.out.println("regDate  :  "+regDate);
				DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
					try {
						regDate = (Date)formatter.parse(regDate.toString());
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				Integer readCount=0;
        		PublicOfficialBuildingBoards buildingBoard = new PublicOfficialBuildingBoards(title, content ,name, regDate, readCount);
        		buildingBoard.setPublicOfficialBuilding(building);
        		Set buildingInfoSet = new HashSet();
    			buildingInfoSet.add(buildingBoard);
    			building.setPOBBoard(buildingInfoSet);
    			buildingService.merge(building);
    		
		} catch (NoResultException e) {

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	System.out.println("ㅎㅎ post도 통과" );
		return "redirect:/umj/pobuilding/showList/"+buildingNo;
    }
    
    //자치센터 리스트보여지는 페이지
    @RequestMapping(value = "/showList/{buildingNo}", method = RequestMethod.GET)
	public ModelMap goBoardList(@PathVariable String buildingNo, ModelMap modelMap, HttpServletRequest request) {
    	Tbbi001 gisBuildingInfo = postgisService.findByBuildingNo(buildingNo);
    	PublicOfficialBuildings building = buildingService.findByPobNo(buildingNo);
    	Long id = building.getId();     					
			
		String pageNum = (String) request.getParameter("pageNum");
		
		int pageNumInt;
		if(request.getParameter("pageNum")==null){
			pageNumInt=1;
			
		}else{
			pageNumInt = Integer.parseInt(pageNum);
		}
		int pagePerArticle = 2;		
		Page page = new Page("/umanji/umj/pobuilding/showList/"+buildingNo, pageNum, pagePerArticle, 4);//페이지 버튼 만드는 메소드(url,페이지번호,한페이지에 보여질글수,페이징버튼갯수)
		
		Long totalArticles = pobBoardService.count();
		page.setMaxRecordCount(Integer.parseInt(totalArticles.toString())-8);
		List li = buildingService.findByBuildingId(id, pageNumInt * pagePerArticle -pagePerArticle+1, pagePerArticle);//페이징 처리 리스트 메소드		
		ModelMap model = new ModelMap("gisBuildingInfo", gisBuildingInfo);
		model.addAttribute("list", li);
		model.addAttribute("pageNum",page.getList());
		System.out.println("showList get 통과");
		return model;
	}
    
    //자치센터 글보기 페이지
    @RequestMapping(value = "/showBoard/{buildingNo}", method = RequestMethod.GET)
	public ModelMap showBoard(@PathVariable String buildingNo, ModelMap modelMap, @RequestParam("boardId")Long boardId) {
    	Tbbi001 gisBuildingInfo = postgisService.findByBuildingNo(buildingNo);

    	System.out.println("count 시작");
    	pobBoardService.getBoardReadCount(boardId);
    	System.out.println("count 끝");

    	PublicOfficialBuildingBoards board = buildingService.findByBoardId(boardId);

    	int readCount = board.getReadCount();
    	System.out.println("readCount+1  ::  "+readCount+1);
    	board.setReadCount(readCount+1);
    	pobBoardService.merge(board);
    	
    	modelMap.addAttribute("board", board);
    	modelMap.addAttribute("gisBuildingInfo", gisBuildingInfo);
		System.out.println("showBoard get 통과");
		return modelMap;		
	}
    
    

}
